import { computed, PropType } from 'vue'
import { defineComponent, ref, onMounted, onBeforeUnmount, getCurrentInstance } from "vue";
import addEventListener from '../_util/Dom/addEventListener';
import Tooltip from "../tooltip";

export default defineComponent({
  props: {
    prefixCls: String,
    value: Number,
    disabled: Boolean,
    min: Number,
    max: Number,
    formatTooltip: Function as PropType<(value: number) => any>,
    tooltip: Boolean,
    onMousedown: Function,
    onMouseup: Function
  },
  setup(props, { attrs, emit, expose }){
    const { proxy: self } = getCurrentInstance()
    const handleRef = ref<HTMLDivElement>()
    const focused = ref(false)

    const ratio = computed(() => (props.value - props.min) / (props.max - props.min))

    //expose({
    //  focus() {
    //    handleRef.value.focus()
    //  },
    //  blur() {
    //    handleRef.value.blur(   )
    //  }
    //})

    // ====================== onMouseup ======================
    let onMouseUpListener
    onMounted(() => {
      onMouseUpListener = addEventListener(document, 'mouseup', onMouseup)
    })
    onBeforeUnmount(() => {
      onMouseUpListener.remove()
    })

    function onBlur() {
      focused.value = false
    }
    function onFocus() {
      focused.value = true
    }
    function onMousedown(e) {
      focused.value = true
      handleRef.value.focus()
      props.onMousedown?.(e)
    }
    function onMouseup(e) {
      props.onMouseup?.(e)
    }

    return () => {
      const { prefixCls, value, formatTooltip, tooltip } = props

      const ariaProps = {
        'aria-valuemin': props.min,
        'aria-valuemax': props.max,
        'aria-valuenow': props.value,
        'aria-disabled': !!props.disabled,
      };

      const handleProps = {
        ref: handleRef,
        class: [`${prefixCls}_handle`, {
          [`${prefixCls}_handle-focused`]: focused.value
        }],
        style: `left: ${ratio.value * 100}%`,
        role: 'slider',
        tabindex: 0,
        ...ariaProps,
        onBlur,
        onFocus,
        onMousedown,
        onMouseup
      }
      
      return (
        <Tooltip title={formatTooltip?.(value) || value} visible={tooltip} placement="top" trigger='hover focus' popupClass={`${prefixCls}-tooltip`}>
          <div {...handleProps}></div>
        </Tooltip>
      )
    }
  }
})